﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;

namespace fgbt_move
{
    public class WebAccess
    {
        public static string EncodePost(string input)
        {
            string output = null;
            Char[] reserved = { '?', '=', '&' };
            if (input != null)
            {
                int i = 0, j;
                while (i < input.Length)
                {
                    j = input.IndexOfAny(reserved, i);
                    if (j == -1)
                    {
                        output = output + HttpUtility.UrlEncode(input.Substring(i, input.Length - i), System.Text.Encoding.GetEncoding("utf-8"));
                        break;
                    }
                    string tt = HttpUtility.UrlEncode(input.Substring(i, j - i), System.Text.Encoding.GetEncoding("utf-8"));
                    output += tt;
                    output += input.Substring(j, 1);
                    i = j + 1;
                }
                return output;
            }
            else
                return null;
        }
        public static string GetWebResponse(string url)
        {
            return GetWebResponse(url, "");
        }
        public static string GetWebResponse(string url, ref CookieCollection cookies)
        {
            return GetWebResponse(url, "", ref cookies);
        }

        public static string GetWebResponse(string url, string poststr)
        {
            CookieCollection a = new CookieCollection();
            return GetWebResponse(url, poststr, ref a);
        }

        public static string GetWebResponse(string url, string username, string password)
        {
            CookieCollection a = new CookieCollection();
            return GetWebResponse(url, ref a, username, password);
        }

        public static string GetWebResponse(string url, ref CookieCollection cookies, string username, string password)
        {
            return GetWebResponse(url, "", "GET", "User-Agent: Mozilla/4.0 (compatible;FGBT AutoSeeder 2.0B; MSIE 7.0; windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322)", "", ref cookies, username, password);
        }

        public static string GetWebResponse(string url, string poststr, ref CookieCollection cookies)
        {
            if (poststr.Trim() == "")
            {
                return GetWebResponse(url, "", "GET", "User-Agent: Mozilla/4.0 (compatible;FGBT AutoSeeder 2.0B; MSIE 7.0; windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322)", poststr, ref cookies, "", "");
            }
            else
            {
                return GetWebResponse(url, "", "POST", "User-Agent: Mozilla/4.0 (compatible;FGBT AutoSeeder 2.0B; MSIE 7.0; windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322)", poststr, ref cookies, "", "");
            }
        }



        /// <summary>
        /// 提交WEB请求并获取返回值
        /// </summary>
        /// <param name="url"></param>
        /// <param name="contenttype"></param>
        /// <param name="method"></param>
        /// <param name="useragent"></param>
        /// <param name="poststr"></param>
        /// <param name="cookies"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string GetWebResponse(string url, string contenttype, string method, string useragent, string poststr, ref CookieCollection cookies, string username, string password)
        {
            string responseHTML = string.Empty;

            if (method.ToLower() == "post") method = "POST";
            else method = "GET";

            try
            {
                HttpWebRequest BBSRequest = null;
                HttpWebResponse BBSResponse = null;

                poststr = EncodePost(poststr);
                byte[] replybyte = null;


                BBSRequest = (HttpWebRequest)WebRequest.Create(url);
                CookieContainer cookieCon = new CookieContainer();
                BBSRequest.CookieContainer = cookieCon;
                cookieCon.Add(cookies);
                BBSRequest.Accept = "*/*";
                BBSRequest.AllowAutoRedirect = false;
                BBSRequest.Headers.Add("Accept-Language", "zh-cn");
                BBSRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                BBSRequest.KeepAlive = true;
                BBSRequest.Timeout = 300000;
                BBSRequest.Method = method;
                BBSRequest.UserAgent = useragent;

                if (username != "" && password != "")
                {
                    BBSRequest.Credentials = new System.Net.NetworkCredential(username, password);
                }

                //POST方法
                if (method == "POST" && poststr.Length != 0)
                {
                    replybyte = Encoding.UTF8.GetBytes(poststr);
                    BBSRequest.ContentType = contenttype;
                    BBSRequest.ContentLength = replybyte.Length;
                    Stream newStream = BBSRequest.GetRequestStream();
                    newStream.Write(replybyte, 0, replybyte.Length);
                    newStream.Close();
                }

                //返回HTML
                BBSResponse = (HttpWebResponse)BBSRequest.GetResponse();
                Stream dataStream = BBSResponse.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("utf-8"));
                responseHTML = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();

                cookies.Add(BBSResponse.Cookies);

                return responseHTML;

            }
            catch (System.Exception ex)
            {
                WorkLog.Add(3, "HTTP读取网址出错：" + ex.ToString());
                return "";
            }
        }

    }
}
